﻿using System.Web;
using Microsoft.TeamFoundation.Framework.Server;
using Microsoft.TeamFoundation.Framework.Server.WebServices;

namespace TfsRollUp.Web
{
    /// <summary>
    /// Summary description for TfsRollUp.Web.Manager
    /// </summary>
    public class Manager : TeamFoundationHttpHandler
    {
        /// <summary>
        /// ctor
        /// </summary>
        public Manager()
            : base(ServiceHostRequirement.ApplicationHostOnly)
        {
        }

        /// <summary>
        /// Process requests to the TfsRollUp.Core.Service
        /// Supports <see cref="TfsRollUp.Core.Settings.EnableRollUpProcesing"/> and <see cref="TfsRollUp.Core.Settings.AddWorkItemToMonitorList"/>
        /// </summary>
        /// <param name="context">The request data</param>
        public override void ProcessRequest(HttpContext context)
        {
            var service = base.RequestContext.GetService<Core.Service>();
            if (service == null)
            {
                var msg = "TfsRollUp.Core.Service could not be located";
                context.Response.Write(msg);
                context.Response.Status = msg;
                context.Response.StatusCode = 501;
                return;
            }

            string enableProcessingString = context.Request.Params["EnableProcessing"];
            if (!string.IsNullOrWhiteSpace(enableProcessingString))
            {
                bool enableProcessing;
                if (bool.TryParse(enableProcessingString, out enableProcessing))
                {
                    service.Settings.EnableRollUpProcesing = enableProcessing;
                    context.Response.Write("EnableProcessing is set to " + enableProcessing);
                    context.Response.StatusCode = 200;
                }
            }

            string workItemIdString = context.Request.Params["WorkItemId"];
            if (!string.IsNullOrWhiteSpace(workItemIdString))
            {
                int workItemId;
                if (int.TryParse(workItemIdString, out workItemId))
                {
                    var isOnMonitorList = service.Settings.IsWorkItemOnMonitorList(workItemId);
                    service.Settings.AddWorkItemToMonitorList(workItemId, !isOnMonitorList);
                    context.Response.Write(string.Format("WorkItemId:{0} monitored:{1}", workItemId, !isOnMonitorList));
                    context.Response.StatusCode = 200;
                }
            }
        }
    }
}